<template>
  <div class="user-avatar-container">
    <el-dropdown @command="handleCommand" trigger="click">
      <div class="avatar-wrapper">
        <el-avatar 
          :size="40" 
          :src="anonymousAvatar"
          class="user-avatar"
        >
          {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
        </el-avatar>
        <span class="username">{{ userInfo.username || '用户' }}</span>
        <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="profile">
            <el-icon><User /></el-icon>
            个人中心
          </el-dropdown-item>
          <el-dropdown-item command="logout" divided>
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { ArrowDown, User, SwitchButton } from '@element-plus/icons-vue'
import anonymousAvatar from '@/assets/anonymous.jpeg'

/**
 * 用户头像下拉菜单组件
 * @author Logan.Li
 */

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 处理下拉菜单命令
const handleCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      try {
        await userStore.logout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        console.error('退出登录失败:', error)
        ElMessage.error('退出登录失败')
      }
      break
  }
}
</script>

<style scoped>
.user-avatar-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  padding: 4px;
  transition: all 0.3s ease;
  color: white;
  cursor: pointer;
}

.avatar-wrapper:hover {
  transform: translateY(-1px);
}

.user-avatar {
  margin-right: 8px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: bold;
  border-radius: 50% !important;
  object-fit: cover;
}

.username {
  font-size: 14px;
  font-weight: 500;
  margin-right: 4px;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dropdown-icon {
  font-size: 12px;
  transition: transform 0.3s ease;
}

.avatar-wrapper:hover .dropdown-icon {
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .username {
    display: none;
  }
  
  .avatar-wrapper {
    padding: 6px;
  }
}
</style>
